import { createRouter, createWebHistory } from "vue-router";
export const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("../views/Home.vue"),
    meta: {
      title: "首页",
    },
  },
  {
    path: "/hello",
    name: "HelloWorld",
    component: () => import("@/components/HelloWorld.vue"),
    meta: {
      title: "你好",
    },
  },
  {
    path: "/404",
    name: "Error404",
    component: () => import("@/components/Error/Error404.vue"),
    meta: {
      title: "找不到页面",
    },
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
];

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition; // 页面滚动到之前的位置
    } else {
      return { top: 0, left: 0 }; // 页面滚动到顶部
    }
  },
});


router.beforeEach((_to, _from, next) => {
  next();
});
router.afterEach((to) => {
  // 页面标题
  document.title = !to.meta.title ? "首页" : to.meta.title + "";
  console.log("路由切换至: " + to.path);
});

export default router;
